package com.jyu.apts.controller;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jyu.apts.service.CacheService;
import com.jyu.apts.utils.AliyunOSSUtil;
import com.jyu.apts.utils.DateUtil;

@RestController
public class AliyunOssController {
	@Autowired
	CacheService cacheService;
	final static String OSS_CACHE_PREFIX = "oss";
	private static final int EXPIRE_HOURS = 6;//单次生成的url过期时间，单位小时
	
	@RequestMapping("/oss/{objectName}")
	public void getOssObject(@PathVariable("objectName")String objectName,HttpServletResponse response) throws IOException{
		if(objectName == null || objectName.trim().length()==0) {
			return;
		}
		URL url = null;
		if((url = (URL) cacheService.getValue(OSS_CACHE_PREFIX, objectName)) == null) {
			synchronized (AliyunOssController.class) {
				if((url = (URL) cacheService.getValue(OSS_CACHE_PREFIX, objectName)) == null) {
					Date expireDate = DateUtil.addHours(new Date(), EXPIRE_HOURS);
					url = AliyunOSSUtil.generateUrl(expireDate, objectName);
					cacheService.put(OSS_CACHE_PREFIX, objectName, url, expireDate);
				}
			}
		}
		String httpUrl = url.toString();
		String httpsUrl = httpUrl.replaceAll("http", "https");
		response.sendRedirect(httpsUrl);
	}
	
}
